package org.convallaria.infrastruct.db.entity;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * 统一分页结果封装
 * 
 * @author gjh
 * @since 2024-09-24
 */
@Data
@NoArgsConstructor
public class PageResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 当前页码
     */
    private Long current;

    /**
     * 每页显示条数
     */
    private Long size;

    /**
     * 总记录数
     */
    private Long total;

    /**
     * 总页数
     */
    private Long pages;

    /**
     * 数据列表
     */
    private List<T> records;

    /**
     * 是否有上一页
     */
    private Boolean hasPrevious;

    /**
     * 是否有下一页
     */
    private Boolean hasNext;

    /**
     * 是否为首页
     */
    private Boolean isFirst;

    /**
     * 是否为末页
     */
    private Boolean isLast;

    public PageResult(Long current, Long size, Long total, List<T> records) {
        this.current = current;
        this.size = size;
        this.total = total;
        this.records = records != null ? records : Collections.emptyList();
        
        // 计算总页数
        this.pages = size > 0 ? (total + size - 1) / size : 0;
        
        // 计算分页状态
        this.hasPrevious = current > 1;
        this.hasNext = current < pages;
        this.isFirst = current.equals(1L);
        this.isLast = current.equals(pages) || pages == 0;
    }

    /**
     * 从 MyBatis-Plus IPage 转换
     */
    public static <T> PageResult<T> of(IPage<T> page) {
        return new PageResult<>(
            page.getCurrent(),
            page.getSize(), 
            page.getTotal(),
            page.getRecords()
        );
    }

    /**
     * 创建空的分页结果
     */
    public static <T> PageResult<T> empty() {
        return new PageResult<>(1L, 10L, 0L, Collections.emptyList());
    }

    /**
     * 创建空的分页结果（指定分页参数）
     */
    public static <T> PageResult<T> empty(Long current, Long size) {
        return new PageResult<>(current, size, 0L, Collections.emptyList());
    }

    /**
     * 创建单页结果
     */
    public static <T> PageResult<T> of(List<T> records) {
        return new PageResult<>(1L, (long) records.size(), (long) records.size(), records);
    }

    /**
     * 检查是否有数据
     */
    public boolean hasRecords() {
        return records != null && !records.isEmpty();
    }

    /**
     * 获取记录数量
     */
    public int getRecordCount() {
        return records != null ? records.size() : 0;
    }

    /**
     * 获取分页信息描述
     */
    public String getPageInfo() {
        if (total == 0) {
            return "暂无数据";
        }
        
        long start = (current - 1) * size + 1;
        long end = Math.min(current * size, total);
        
        return String.format("第 %d-%d 条，共 %d 条记录，第 %d/%d 页", 
            start, end, total, current, pages);
    }
}
